package com.taijihuabao.modules.service.impl;

import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.PageHelper;
import com.taijihuabao.common.commonutils.BusinessIdUtil;
import com.taijihuabao.common.commonutils.DateFormatUtil;
import com.taijihuabao.common.commonutils.PageResult;
import com.taijihuabao.common.emailutils.EmailPojo;
import com.taijihuabao.common.exception.ServiceException;
import com.taijihuabao.common.jsonresult.ApplicationResponseCode;
import com.taijihuabao.common.rabbitmq.RabbitMqProducer;
import com.taijihuabao.common.redisconfig.UserLoad;
import com.taijihuabao.modules.entity.*;
import com.taijihuabao.modules.enums.optenums.approval.ApprovalStatusEnum;
import com.taijihuabao.modules.enums.optenums.approval.BusinessEnum;
import com.taijihuabao.modules.enums.optenums.checkin.CheckInStatusEnum;
import com.taijihuabao.modules.enums.optenums.checkin.CheckInWorkEnum;
import com.taijihuabao.modules.enums.optenums.checkin.ReissueCardEnum;
import com.taijihuabao.modules.enums.optenums.dept.DeptEnum;
import com.taijihuabao.modules.enums.optenums.dept.DeptRoleEnum;
import com.taijihuabao.modules.mapper.*;
import com.taijihuabao.modules.model.approval.dto.ApprovalProcessDTO;
import com.taijihuabao.modules.model.approval.vo.ApprovalVO;
import com.taijihuabao.modules.model.approval.dto.ApproveCompleteDTO;
import com.taijihuabao.modules.model.reissuecard.vo.ReissueCardApprovalVO;
import com.taijihuabao.modules.model.reissuecard.vo.ReissueCardVO;
import com.taijihuabao.modules.model.user.vo.UserInfoVO;
import com.taijihuabao.modules.service.ApprovalProcessService;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.RuntimeService;
import org.activiti.engine.TaskService;
import org.activiti.engine.task.Task;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.*;

/**
 * 补卡审批流程实现类
 *
 * @author Tu
 * @date 2022/1/10 18:56
 */
@Service
public class ReissueCardApprovalServiceImpl implements ApprovalProcessService {

    /**
     * 审批节点名及自动审批信息
     */
    private static final String APPROVAL_TASK_NAME = "审批人";
    private static final String ADMIN_TASK_NAME = "连续多级主管";
    private static final String CHECKIN_ATTACHE_TASK_NAME = "考勤专员";
    private static final String[] WEEKDAYS = {"周日", "周一", "周二", "周三", "周四", "周五", "周六"};
    private static final String AUTO_COMPARE_REMARK_MESSAGE = "连续主管自动审批";
    private static final String AUTO_REAPPLY = "驳回修改完毕";

    @Resource
    private RepositoryService repositoryService;
    @Resource
    private RuntimeService runtimeService;
    @Resource
    private TaskService taskService;
    @Resource
    private ApprovalMapper approvalMapper;
    @Resource
    private ApprovalHistoryMapper approvalHistoryMapper;
    @Resource
    private ApprovalBusinessMapper approvalBusinessMapper;
    @Resource
    private ReissueCardMapper reissueCardMapper;
    @Resource
    private ReissueCardHistoryMapper reissueCardHistoryMapper;
    @Resource
    private UserMapper userMapper;
    @Resource
    private DeptUserMapper deptUserMapper;
    @Resource
    private DeptMapper deptMapper;
    @Resource
    private RabbitMqProducer rabbitMqProducer;
    @Resource
    private CheckInMapper checkInMapper;

    @Override
    public void deploy() {
        repositoryService.createDeployment()
                .addClasspathResource("bpmn/ReissueCard.bpmn")
                .addClasspathResource("bpmn/ReissueCard.png")
                .name("补卡审批流程")
                .deploy();

    }

    @Override
    public List<ReissueCardApprovalVO> findTask(String processName) {
        //查询登录用户任务
        List<Task> taskList = taskService.createTaskQuery()
                .processDefinitionKey(ReissueCardEnum.ReissueCardKey.getCode())
                .taskAssignee(String.valueOf(UserLoad.getUser().getId())).list();
        List<ReissueCardApprovalVO> reissueCardApprovalList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(taskList)) {
            for (Task task : taskList) {
                long businessKey = Long.parseLong(task.getBusinessKey());
                //获取数据
                ApprovalEntity approvalEntity = approvalMapper.selectById(businessKey);
                if (approvalEntity != null) {
                    ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalEntity.getApprovalCode());
                    ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
                    //数据转换
                    ApprovalVO approvalVO = new ApprovalVO();
                    BeanUtils.copyProperties(approvalEntity, approvalVO);
                    ReissueCardVO reissueCardVO = new ReissueCardVO();
                    approvalVO.setApprovalTask(task.getId());
                    BeanUtils.copyProperties(reissueCardEntity, reissueCardVO);
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(reissueCardEntity.getReissueTime());
                    String week = WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
                    reissueCardVO.setReissueShift(DateFormatUtil.formatDate(reissueCardEntity.getReissueTime()) + "," + week);
                    reissueCardVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                    reissueCardVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                    //数据赋值
                    ReissueCardApprovalVO reissueCardApprovalVO = new ReissueCardApprovalVO();
                    reissueCardApprovalVO.setApprovalVO(approvalVO);
                    reissueCardApprovalVO.setReissueCardVO(reissueCardVO);
                    reissueCardApprovalList.add(reissueCardApprovalVO);
                }
            }
        }
        return reissueCardApprovalList;
    }

    @Override
    public List<ReissueCardApprovalVO> findCompleteTask(String processName) {
        //定义对象
        List<ReissueCardApprovalVO> reissueCardApprovalList = new ArrayList<>();
        //查询审批历史数据
        List<ApprovalVO> approvalHistoryList = approvalHistoryMapper.selectByApprovalUserId(UserLoad.getUser().getId());
        for (ApprovalVO approvalVO : approvalHistoryList) {
            //查询补卡数据
            ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalVO.getApprovalCode());
            ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
            if (reissueCardEntity != null) {
                //数据转换
                ReissueCardVO reissueCardVO = new ReissueCardVO();
                BeanUtils.copyProperties(reissueCardEntity, reissueCardVO);
                Calendar cal = Calendar.getInstance();
                cal.setTime(reissueCardEntity.getReissueTime());
                String week = WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
                reissueCardVO.setReissueShift(DateFormatUtil.formatDate(reissueCardEntity.getReissueTime()) + "," + week);
                reissueCardVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                reissueCardVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                //赋值数据
                ReissueCardApprovalVO reissueCardApprovalVO = new ReissueCardApprovalVO();
                reissueCardApprovalVO.setApprovalVO(approvalVO);
                reissueCardApprovalVO.setReissueCardVO(reissueCardVO);
                reissueCardApprovalList.add(reissueCardApprovalVO);
            }
        }
        return reissueCardApprovalList;
    }

    @Override
    public List<ReissueCardApprovalVO> findActivities(String approvalCode) {
        List<ReissueCardApprovalVO> reissueCardApprovalList = new ArrayList<>();
        List<ApprovalVO> approvalVOList = approvalHistoryMapper.selectByApprovalCode(approvalCode);
        for (ApprovalVO approvalVO : approvalVOList) {
            approvalVO.setApprovalUserName(userMapper.selectById(approvalVO.getApprovalUserId()).getName());
            ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalCode);
            ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
            if (reissueCardEntity != null) {
                //数据转换
                ReissueCardVO reissueCardVO = new ReissueCardVO();
                BeanUtils.copyProperties(reissueCardEntity, reissueCardVO);
                Calendar cal = Calendar.getInstance();
                cal.setTime(reissueCardEntity.getReissueTime());
                String week = WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
                reissueCardVO.setReissueShift(DateFormatUtil.formatDate(reissueCardEntity.getReissueTime()) + "," + week);
                reissueCardVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                reissueCardVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                //赋值数据
                ReissueCardApprovalVO reissueCardApprovalVO = new ReissueCardApprovalVO();
                reissueCardApprovalVO.setApprovalVO(approvalVO);
                reissueCardApprovalVO.setReissueCardVO(reissueCardVO);
                reissueCardApprovalList.add(reissueCardApprovalVO);
            }
        }
        return reissueCardApprovalList;
    }

    @Override
    public PageResult<T> selectByApplyUserId(int page, int size) {
        PageHelper.startPage(page, size);
        UserEntity userEntity = UserLoad.getUser();
        List<ApprovalVO> approvalVOList = approvalMapper.selectByApplyUserId(userEntity.getId());
        List<ApprovalVO> newApprovalList = new ArrayList<>();
        if (!CollectionUtils.isEmpty(approvalVOList)) {
            for (ApprovalVO approvalVO : approvalVOList) {
                //筛选补卡审批单
                if (approvalVO.getApprovalCode().contains(BusinessEnum.Re_Card.getCode())) {
                    ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalVO.getApprovalCode());
                    ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
                    approvalVO.setApplyContent(approvalBusinessEntity.getApplyContent());
                    approvalVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
                    approvalVO.setReissueCode(reissueCardEntity.getReissueCode());
                    approvalVO.setReissueTime(reissueCardEntity.getReissueTime());
                    Calendar cal = Calendar.getInstance();
                    cal.setTime(reissueCardEntity.getReissueTime());
                    String week = WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
                    approvalVO.setReissueShift(DateFormatUtil.formatDate(reissueCardEntity.getReissueTime()) + "," + week);
                    newApprovalList.add(approvalVO);
                }
            }
        }
        return new PageResult(newApprovalList);
    }

    @Override
    public ApprovalVO selectByApprovalCode(String approvalCode) {
        ApprovalVO approvalVO = approvalMapper.selectByApprovalCode(approvalCode);
        if (!Objects.isNull(approvalVO)) {
            ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalVO.getApprovalCode());
            ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
            approvalVO.setApplyContent(approvalBusinessEntity.getApplyContent());
            approvalVO.setApplyRemarks(approvalBusinessEntity.getApplyRemarks());
            approvalVO.setReissueCode(reissueCardEntity.getReissueCode());
            approvalVO.setReissueTime(reissueCardEntity.getReissueTime());
            Calendar cal = Calendar.getInstance();
            cal.setTime(reissueCardEntity.getReissueTime());
            String week = WEEKDAYS[cal.get(Calendar.DAY_OF_WEEK) - 1];
            approvalVO.setReissueShift(DateFormatUtil.formatDate(reissueCardEntity.getReissueTime()) + "," + week);
        }
        return approvalVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String startProcess(ApprovalProcessDTO approvalProcessDTO) {
        //获取对象
        ApprovalBusinessEntity approvalBusinessEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ApprovalBusinessEntity.class);
        ReissueCardEntity reissueCardEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ReissueCardEntity.class);
        ReissueCardHistoryEntity reissueCardHistoryEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ReissueCardHistoryEntity.class);
        //添加业务主表数据
        String approvalBusinessId = BusinessIdUtil.createBusinessId(BusinessEnum.Re_Card.getCode());
        approvalBusinessEntity.setBusinessId(approvalBusinessId);
        approvalBusinessEntity.setApplyType(BusinessEnum.Re_Card.getCode());
        approvalBusinessEntity.setApplyCode(approvalBusinessId);
        approvalBusinessMapper.insertApprovalBusiness(approvalBusinessEntity);
        //添加补卡数据
        reissueCardEntity.setReissueCode(approvalBusinessId);
        reissueCardMapper.addReissueCard(reissueCardEntity);
        //添加补卡历史
        reissueCardHistoryEntity.setReissueCode(approvalBusinessId);
        reissueCardHistoryMapper.insertReissueCardHistory(reissueCardHistoryEntity);
        //添加审批数据
        ApprovalEntity approvalEntity = new ApprovalEntity();
        approvalEntity.setApprovalType(BusinessEnum.Re_Card.getCode());
        approvalEntity.setApprovalCode(approvalBusinessId);
        Long loginUserId = UserLoad.getUser().getId();
        approvalEntity.setApplyUserId(loginUserId);
        UserInfoVO userInfoVO = userMapper.selectById(loginUserId);
        approvalEntity.setApplyName(userInfoVO.getName());
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByUserId(userInfoVO.getId());
        approvalEntity.setApplyDeptCode(deptUserEntities.get(0).getDeptCode());
        approvalMapper.insertApproval(approvalEntity);
        //启动并添加business_key（补卡单id）
        runtimeService.startProcessInstanceByKey(ReissueCardEnum.ReissueCardKey.getCode(), String.valueOf(approvalEntity.getId()));
        //修改状态为启动
        approvalMapper.updateApprovalIng(approvalEntity.getId());
        //设置驳回处理负责人为自己
        taskService.setVariable(getTask(approvalEntity.getId()).getId(), "submitPerson", loginUserId);
        return approvalEntity.getApprovalCode();
    }

    @Override
    public void completeTask(ApproveCompleteDTO approveCompleteDTO) {
        //获取用户、任务id
        Long loginUserId = UserLoad.getUser().getId();
        String taskId = approveCompleteDTO.getTaskId();
        //获取任务及businessKey
        Task task = taskService.createTaskQuery().taskId(approveCompleteDTO.getTaskId()).singleResult();
        Long businessKey = Long.valueOf(task.getBusinessKey());
        //获取补卡审批单
        ApprovalEntity approvalEntity = approvalMapper.selectById(businessKey);
        //设置变量
        Map<String, Object> map = new HashMap<>(7);
        //获取枚举
        ApprovalStatusEnum option = ApprovalStatusEnum.getByCode(String.valueOf(approveCompleteDTO.getAgree()));
        if (option != null) {
            //设置审批数据
            approvalEntity.setApprovalUserId(loginUserId);
            String deptCode = deptUserMapper.selectDeptByUserId(loginUserId).get(0).getDeptCode();
            approvalEntity.setApprovalDeptCode(deptCode);
            approvalEntity.setApprovalOpinion(approveCompleteDTO.getApprovalOpinion());
            approvalEntity.setApprovalTask(taskId);
            //添加审批历史
            ApprovalHistoryEntity approvalHistoryEntity = getApprovalHisEntity(approvalEntity);
            approvalHistoryEntity.setApprovalOpinion(approveCompleteDTO.getApprovalOpinion());
            approvalHistoryEntity.setApprovalTask(taskId);
            approvalHistoryEntity.setApprovalFlow(task.getName());
            switch (task.getName()) {
                case APPROVAL_TASK_NAME:
                    //设置审核意见
                    map.put(ReissueCardEnum.ApproverOpinion.getCode(), approveCompleteDTO.getAgree());
                    switch (option) {
                        case ApprovePass:
                            //处理任务,添加数据
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_PASS.getCode());
                            taskService.complete(taskId, map, true);
                            //审核通过查询父部门主管
                            List<DeptUserEntity> allPersons = deptUserMapper.selectDeptByUserId(UserLoad.getUser().getId());
                            DeptEntity deptEntity = deptMapper.selectDeptByCode(allPersons.get(0).getDeptCode());
                            String parentDept = deptEntity.getParentDept();
                            List<DeptUserEntity> parentDeptPersons = deptUserMapper.selectDeptByDeptCode(parentDept);
                            //是否有父部门及人员
                            boolean adminNotExist = true;
                            if (!CollectionUtils.isEmpty(parentDeptPersons)) {
                                for (DeptUserEntity continueUser : parentDeptPersons) {
                                    //父部门是否有主管
                                    if (DeptRoleEnum.Admin.getCode().equals(continueUser.getDeptRole())) {
                                        adminNotExist = false;
                                        break;
                                    }
                                }
                            }
                            if (adminNotExist) {
                                map.put(ReissueCardEnum.AdminOpinion.getCode(), approveCompleteDTO.getAgree());
                                Task continueTask = getTask(businessKey);
                                approvalEntity.setApprovalOpinion(AUTO_COMPARE_REMARK_MESSAGE);
                                approvalEntity.setApprovalTask(continueTask.getId());
                                approvalHistoryEntity.setApprovalOpinion(AUTO_COMPARE_REMARK_MESSAGE);
                                approvalHistoryEntity.setApprovalTask(continueTask.getId());
                                approvalHistoryEntity.setApprovalFlow(continueTask.getName());
                                approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_PASS.getCode());
                                taskService.complete(continueTask.getId(), map, true);
                            }
                            break;
                        case ApproveReject:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REJECT.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        case ApproveRefuse:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REFUSE.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REFUSE.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        default:
                    }
                    break;
                case ADMIN_TASK_NAME:
                    map.put(ReissueCardEnum.AdminOpinion.getCode(), approveCompleteDTO.getAgree());
                    switch (option) {
                        case ApprovePass:
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_PASS.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        case ApproveReject:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REJECT.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        case ApproveRefuse:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REFUSE.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REFUSE.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        default:
                    }
                    break;
                case CHECKIN_ATTACHE_TASK_NAME:
                    map.put(ReissueCardEnum.CheckInAttacheOpinion.getCode(), approveCompleteDTO.getAgree());
                    switch (option) {
                        case ApprovePass:
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_PASS.getCode());
                            taskService.complete(taskId, map, true);
                            approvalComplete(approvalEntity);
                            break;
                        case ApproveReject:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REJECT.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REJECT.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        case ApproveRefuse:
                            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_REFUSE.getCode());
                            approvalData(approvalEntity, approvalHistoryEntity, ApprovalStatusEnum.STATE_REFUSE.getCode());
                            taskService.complete(taskId, map, true);
                            break;
                        default:
                    }
                    break;
                default:
                    throw new ServiceException(ApplicationResponseCode.INTER_ERROR);
            }
        }
    }

    @Override
    public String reSubmit(ApprovalProcessDTO approvalProcessDTO) {
        //转换实体
        ApprovalBusinessEntity formatApprovalBusinessEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ApprovalBusinessEntity.class);
        ReissueCardEntity formatReissueCardEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ReissueCardEntity.class);
        ReissueCardHistoryEntity reissueCardHistoryEntity = JSONObject.parseObject(approvalProcessDTO.getApprovalProcess(), ReissueCardHistoryEntity.class);
        //修改业务主表
        ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectByApplyCode(formatReissueCardEntity.getReissueCode());
        approvalBusinessEntity.setApplyContent(formatApprovalBusinessEntity.getApplyContent());
        approvalBusinessEntity.setApplyRemarks(formatApprovalBusinessEntity.getApplyRemarks());
        approvalBusinessMapper.updateApprovalBusiness(approvalBusinessEntity);
        //修改补卡数据
        ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(formatReissueCardEntity.getReissueCode());
        reissueCardEntity.setReissueTime(formatReissueCardEntity.getReissueTime());
        reissueCardMapper.updateReissueCard(reissueCardEntity);
        //新增补卡历史记录
        reissueCardHistoryEntity.setReissueCode(reissueCardEntity.getReissueCode());
        reissueCardHistoryMapper.insertReissueCardHistory(reissueCardHistoryEntity);
        //修改审批数据
        ApprovalEntity approvalEntity = approvalMapper.selectOne(approvalBusinessEntity.getBusinessId());
        Task task = getTask(approvalEntity.getId());
        approvalEntity.setApprovalUserId(approvalEntity.getApplyUserId());
        approvalEntity.setApprovalDeptCode(approvalEntity.getApplyDeptCode());
        approvalEntity.setApprovalOpinion(AUTO_REAPPLY);
        approvalEntity.setApprovalTask(task.getId());
        approvalMapper.updateApproval(approvalEntity);
        //保存审批历史数据
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalType(approvalEntity.getApprovalType());
        approvalHistoryEntity.setApprovalCode(approvalEntity.getApprovalCode());
        approvalHistoryEntity.setApplyUserId(approvalEntity.getApplyUserId());
        approvalHistoryEntity.setApplyDeptCode(approvalEntity.getApplyDeptCode());
        approvalHistoryEntity.setApplyName(approvalEntity.getApplyName());
        approvalHistoryEntity.setApprovalUserId(approvalEntity.getApprovalUserId());
        approvalHistoryEntity.setApprovalDeptCode(approvalEntity.getApprovalDeptCode());
        approvalHistoryEntity.setApprovalOpinion(AUTO_REAPPLY);
        approvalHistoryEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
        approvalHistoryEntity.setApprovalTask(task.getId());
        approvalHistoryEntity.setApprovalFlow(task.getName());
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
        //完成重新提交
        taskService.complete(task.getId(), null, true);
        return approvalEntity.getApprovalCode();
    }

    @Override
    public String getProcessName() {
        return BusinessEnum.Re_Card.getCode();
    }

    /**
     * 查询任务
     *
     * @param businessKey
     */
    public Task getTask(Object businessKey) {
        return taskService.createTaskQuery()
                .processDefinitionKey(ReissueCardEnum.ReissueCardKey.getCode())
                .processInstanceBusinessKey(String.valueOf(businessKey))
                .singleResult();
    }

    /**
     * 获取审批历史实体类
     *
     * @param approvalEntity 审批数据实体类
     * @return
     */
    public ApprovalHistoryEntity getApprovalHisEntity(ApprovalEntity approvalEntity) {
        ApprovalHistoryEntity approvalHistoryEntity = new ApprovalHistoryEntity();
        approvalHistoryEntity.setApprovalType(approvalEntity.getApprovalType());
        approvalHistoryEntity.setApprovalCode(approvalEntity.getApprovalCode());
        approvalHistoryEntity.setApplyUserId(approvalEntity.getApplyUserId());
        approvalHistoryEntity.setApplyName(approvalEntity.getApplyName());
        approvalHistoryEntity.setApplyDeptCode(approvalEntity.getApplyDeptCode());
        approvalHistoryEntity.setApprovalUserId(approvalEntity.getApprovalUserId());
        approvalHistoryEntity.setApprovalDeptCode(approvalEntity.getApprovalDeptCode());
        return approvalHistoryEntity;
    }

    /**
     * 审批数据操作
     *
     * @param approvalEntity        审批数据实体类
     * @param approvalHistoryEntity 审批历史实体类
     * @param status                状态
     */
    public void approvalData(ApprovalEntity approvalEntity, ApprovalHistoryEntity approvalHistoryEntity, String
            status) {
        approvalMapper.updateApproval(approvalEntity);
        approvalHistoryEntity.setApprovalState(status);
        approvalHistoryMapper.insertApproval(approvalHistoryEntity);
    }

    /**
     * 判断审批是否完成
     *
     * @param approvalEntity
     */
    public void approvalComplete(ApprovalEntity approvalEntity) {
        //获取审批历史集合
        List<ApprovalVO> approvalHis = approvalHistoryMapper.selectByApprovalCode(approvalEntity.getApprovalCode());
        int approvalSum = 0;
        //查询人事部有多少审批
        for (ApprovalVO approvalVO : approvalHis) {
            if (!StringUtils.isEmpty(approvalVO.getApprovalDeptCode())) {
                String ing = ApprovalStatusEnum.STATE_ING.getCode();
                if (DeptEnum.PERSONNEL_DEPT.getCode().equals(approvalVO.getApprovalDeptCode()) && ing.equals(approvalVO.getApprovalState())) {
                    approvalSum++;
                }
            }
        }
        int approvalComplete = 0;
        //查询出此单人事部完成了多少任务
        for (ApprovalVO approvalVO : approvalHis) {
            if (!StringUtils.isEmpty(approvalVO.getApprovalDeptCode())) {
                String pass = ApprovalStatusEnum.STATE_PASS.getCode();
                if (DeptEnum.PERSONNEL_DEPT.getCode().equals(approvalVO.getApprovalDeptCode()) && pass.equals(approvalVO.getApprovalState())) {
                    approvalComplete++;
                }
            }
        }
        //全部完成进行邮件抄送
        if (approvalSum == approvalComplete) {
            approvalEntity.setApprovalState(ApprovalStatusEnum.STATE_PASS.getCode());
            approvalMapper.updateApproval(approvalEntity);
            emailCorbon(approvalEntity);
            //补卡数据录入
            ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalEntity.getApprovalCode());
            ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
            checkInEntering(approvalEntity.getApplyUserId(), reissueCardEntity.getReissueTime());
        }
    }

    /**
     * 邮件抄送
     *
     * @param approvalEntity
     */
    public void emailCorbon(ApprovalEntity approvalEntity) {
        ApprovalBusinessEntity approvalBusinessEntity = approvalBusinessMapper.selectOne(approvalEntity.getApprovalCode());
        ReissueCardEntity reissueCardEntity = reissueCardMapper.getReissueCardByCode(approvalBusinessEntity.getApplyCode());
        //查询部门
        List<DeptUserEntity> deptUserEntities = deptUserMapper.selectDeptByDeptRole(DeptRoleEnum.CheckInPersonnel.getCode());
        List<String> emailList = new ArrayList<>();
        //遍历部门人员查出人事考勤组成员
        for (DeptUserEntity due : deptUserEntities) {
            if (DeptRoleEnum.CheckInPersonnel.getCode().equals(due.getDeptRole())) {
                UserInfoVO userInfoVO = userMapper.selectById(due.getUserId());
                emailList.add(String.valueOf(userInfoVO.getUserEmail()));
            }
        }
        //抄送邮件
        DeptEntity deptEntity = deptMapper.selectDeptByCode(approvalEntity.getApplyDeptCode());
        String content = "申请人：" + approvalEntity.getApplyName() + " \n"
                + " 部门：" + deptEntity.getDeptName() + " \n"
                + "补卡申请：" + DateFormatUtil.formatSimpleDateTime(reissueCardEntity.getReissueTime()) + "\n"
                + "补卡理由：" + approvalBusinessEntity.getApplyRemarks() + " \n"
                + "申请状态：" + (ApprovalStatusEnum.STATE_PASS.getCode().equals(approvalEntity.getApprovalState()) ? "通过" : "拒绝") + " \n";
        EmailPojo emailPojo = new EmailPojo();
        String emailSubject = "【审批通过邮件抄送】";
        emailPojo.setSubject(emailSubject);
        emailPojo.setContent(content);
        emailPojo.setReceiver(emailList);
        rabbitMqProducer.commonMailProducer(emailPojo);
    }

    /**
     * 补卡数据录入
     *
     * @param userId      补卡申请人id
     * @param reissueTime 申请补卡日期
     */
    public void checkInEntering(Long userId, Date reissueTime) {
        CheckInEntity checkInEntity = new CheckInEntity();
        checkInEntity.setDateTime(DateFormatUtil.formatDate(reissueTime));
        checkInEntity.setUid(userId);
        checkInEntity.setClockTime(reissueTime);
        List<CheckInEntity> checkInList = checkInMapper.selCheckInByUid(checkInEntity);
        if (!CollectionUtils.isEmpty(checkInList)) {
            boolean startClockNotExist = true;
            boolean outClockNotExist = true;
            for (CheckInEntity check : checkInList) {
                String clockType = String.valueOf(check.getClockType());
                if (CheckInWorkEnum.StartWork.getCode().equals(clockType)) {
                    startClockNotExist = false;
                }
                if (CheckInWorkEnum.OutWork.getCode().equals(clockType)) {
                    outClockNotExist = false;
                }
            }
            if (startClockNotExist) {
                checkInEntity.setClockType(Long.valueOf(CheckInWorkEnum.StartWork.getCode()));
            }
            if (outClockNotExist) {
                checkInEntity.setClockType(Long.valueOf(CheckInWorkEnum.OutWork.getCode()));
            }
        } else {
            checkInEntity.setClockType(Long.valueOf(CheckInWorkEnum.StartWork.getCode()));
        }
        checkInEntity.setStateId(Long.valueOf(CheckInStatusEnum.Normal.getCode()));
        checkInMapper.attendanceClock(checkInEntity);
    }

}
